﻿#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    desktopPath=QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
    model = new QStringListModel(this);
    categoryModel=new QStringListModel(this);
    ui->listView->setModel(model);
    ui->categoryList->setModel(categoryModel);
    offline=true;
    current_category="NULL";
    current_item="NULL";
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::on_btn_load_clicked()
{
    fileName=QFileDialog::getOpenFileName(this,QStringLiteral("选择一个文件"),desktopPath,"*.json");
    if(fileName.isEmpty())
        return;

    Piev piev(fileName);
    piev.setDetailTag(DETAIL_T);
    if(piev.load())
    {
        ui->in_category->setText(piev.get(LABEL_T));
        QStringList list=piev.getStringList();
        model->setStringList(list);
    }
    else
        QMessageBox::warning(this,QStringLiteral("加载失败"),QStringLiteral("文件加载失败！"));
}

void Dialog::on_btn_add_clicked()
{
    QString category=ui->in_category->text().trimmed();
    if(category.isEmpty())
    {
        QMessageBox::warning(this,QStringLiteral("不能为空"),QStringLiteral("类别不能为空！"));
        return;
    }

    QString prop=ui->in_prop->text().trimmed();
    if(prop.isEmpty())
        return;

    if(category !=current_category)
    {
        current_category=category;
        model->setStringList(QStringList());
    }

    int row=model->rowCount();
    model->insertRow(row);
    QModelIndex index=model->index(row);
    model->setData(index,prop);
    ui->in_prop->clear();
}

void Dialog::on_btn_del_clicked()
{
    int row=ui->listView->currentIndex().row();
    model->removeRow(row);
}

void Dialog::on_btn_save_clicked()
{
    QString category=ui->in_category->text().trimmed();
    if(category.isEmpty())
    {
        QMessageBox::warning(this,QStringLiteral("不能为空"),QStringLiteral("类别不能为空！"));
        return;
    }

    if(offline)
    {
        if(fileName.isEmpty())
        {
            fileName=QInputDialog::getText(this,QStringLiteral("输入文件名"),QStringLiteral("文件名："));
            if(fileName.isEmpty())
                return;

            fileName=desktopPath + QString("/") + fileName + QString(".json");
        }

        Piev piev(fileName);
        piev.put(LABEL_T,category);
        piev.put("category","_meta_");
        piev.put(DETAIL_T,QJsonArray::fromStringList(model->stringList()));
        if(piev.save())
        {
            QString word= QStringLiteral("文件已保存为：\n") + fileName;
            QMessageBox::information(this,QStringLiteral("保存完成"),
                                     word,QMessageBox::Ok);
        }
    }
    else
    {

        if(category !=current_category)
        {
            qDebug() << "here-1";
            current_category=category;

            QJsonObject obj;
            obj.insert(LABEL_T,category);
            obj.insert("category","_meta_");
            obj.insert(DETAIL_T,QJsonArray::fromStringList(model->stringList()));

            QString url=base_url + "put";
            request.setUrl(QUrl(url));

            QJsonDocument doc(obj);
            manager->post(request,doc.toJson());
        }
        else
        {
            qDebug() << "here-2";
            QJsonObject selector;
            selector.insert(LABEL_T,category);
            selector.insert("category","_meta_");

            QJsonObject updater;
            updater.insert(DETAIL_T,QJsonArray::fromStringList(model->stringList()));

            QJsonArray array;
            array.append(selector);
            array.append(updater);

            QString url=base_url + "update";
            request.setUrl(QUrl(url));

            QJsonDocument doc(array);
            manager->post(request,doc.toJson());
        }
    }
}

bool Dialog::load(const QString &file)
{
    Pie pie(file);
    if(pie.load())
    {
        manager=new QNetworkAccessManager(this);
        connect(manager,&QNetworkAccessManager::finished,this,&Dialog::replyFinished);
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

        QString url=pie.get("base");
        base_url=url + "item/";
        reply = manager->get(QNetworkRequest(QUrl(base_url)));
        connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(un_reach()));

        return true;
    }
    else
        return false;
}

void Dialog::un_reach()
{
    QMessageBox::critical(this,QStringLiteral("无法连接"),QStringLiteral("无法连接到服务器！"));
}

void Dialog::on_btn_online_clicked()
{
    if(load())
    {
        offline=false;
        QString url=base_url + "categories";
        manager->get(QNetworkRequest(QUrl(url)));
    }
}

void Dialog::replyFinished(QNetworkReply *reply)
{
    QByteArray data=reply->readAll();
    qDebug() << data;

    Pie pie(data);
    if(pie.contain("properties"))
    {
        Piev piev(data,"properties");
        ui->in_category->setText(piev.get("label"));
        current_category=piev.get("label");

        QStringList list=piev.getStringList();
        model->setStringList(list);
    }
    else if(pie.contain("categories"))
    {
        Piev piev(data,"categories");
        QStringList list=piev.getStringList();
        categoryModel->setStringList(list);
    }
}

void Dialog::on_categoryList_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        model->setStringList(QStringList());
        current_item=categoryModel->data(index,Qt::DisplayRole).toString();

        QJsonObject selector;
        selector.insert(LABEL_T,category);
        selector.insert("category","_meta_");

        QString url=base_url + "get_one";
        request.setUrl(QUrl(url));

        QJsonDocument doc(selector);
        manager->post(request,doc.toJson());
    }
}

void Dialog::on_btn_view_clicked()
{
    QString category=ui->in_category->text().trimmed();
    if(category.isEmpty())
        return;

    QJsonObject obj;
    obj.insert(LABEL_T,category);
    obj.insert("category","_meta_");
    obj.insert(DETAIL_T,QJsonArray::fromStringList(model->stringList()));

    QJsonDocument doc(obj);
    ui->panView->setPlainText(doc.toJson());
}
